package com.ruoyi.ocean.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.bytedance.ads.ApiClient;
import com.bytedance.ads.ApiException;
import com.bytedance.ads.Pair;
import com.bytedance.ads.api.*;
import com.bytedance.ads.model.*;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.redis.RedisUtils;
import com.ruoyi.ocean.domain.OceanAccount;
import com.ruoyi.ocean.domain.OceanLogTotal;
import com.ruoyi.ocean.domain.bo.OceanAccountBo;
import com.ruoyi.ocean.domain.bo.OceanLogBo;
import com.ruoyi.ocean.domain.vo.OceanAccountVo;
import com.ruoyi.ocean.domain.vo.OceanUserVo;
import com.ruoyi.ocean.service.IOceanAccountService;
import com.ruoyi.ocean.service.IOceanLogService;
import com.ruoyi.ocean.service.IOceanUserService;
import com.ruoyi.ocean.service.OpenApiService;
import com.ruoyi.ocean.utils.OpenEnum;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 操作日志Service接口
 *
 * @author linziheng
 * @date 2024-05-08
 */
@RequiredArgsConstructor
@Service
public class OpenApiServiceImpl implements OpenApiService {
    private static final CommonReqApi api = new CommonReqApi();
    private static final Oauth2AdvertiserGetApi advertiserGetApi = new Oauth2AdvertiserGetApi();
    private static final Oauth2RefreshTokenApi refreshTokenApi = new Oauth2RefreshTokenApi();
    private static final ToolsLogSearchV2Api searchV2Api = new ToolsLogSearchV2Api();
    private static final AgentAdvertiserSelectV2Api selectV2Api = new AgentAdvertiserSelectV2Api();
    private final IOceanAccountService iOceanAccountService;
    private final IOceanUserService iOceanUserService;
    private final IOceanLogService iOceanLogService;
    private static final ReportAgentGetV2V2Api reportAgentGetV2V2Api = new ReportAgentGetV2V2Api();
    /**
     * 刷新token
     */
    @Override
    public void refToken(){
        List<Map<String, Object>> list = getParams();
        for (Map<String, Object> map : list) {
            try {
                refreshToken(map);
            } catch (ApiException e) {
                e.printStackTrace();
            }
        }
    }

    public List<Map<String, Object>> getParams(){
        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> list = new ArrayList<>();
        map.put("app_id", OpenEnum.ZRX_AD_APP_ID);
        map.put("secret", OpenEnum.ZRX_AD_SECRET);
        map.put("access_token", OpenEnum.ZRX_AD_ACCESS_TOKEN);
        map.put("refreshToken", OpenEnum.ZRX_AD_REFRESHTOKEN);
        map.put("auth_code", "fb38a3f297e52f786e2b55e33df41a38744f9e36");
        map.put("advertiser_id", OpenEnum.ZRX_AD_ADVERTISER_ID);
        map.put("type", OpenEnum.ZRX_AD_TYPE);
        map.put("name", OpenEnum.ZRX_AD_NAME);
        list.add(map);
        Map<String, Object> map2 = new HashMap<>();
        map2.put("app_id", OpenEnum.ZRX_QC_APP_ID);
        map2.put("secret", OpenEnum.ZRX_QC_SECRET);
        map2.put("access_token", OpenEnum.ZRX_QC_ACCESS_TOKEN);
        map2.put("refreshToken", OpenEnum.ZRX_QC_REFRESHTOKEN);
        map2.put("auth_code", "942bf627a54ada08da994419475f0eda7f7d3e25");
        map2.put("advertiser_id", OpenEnum.ZRX_QC_ADVERTISER_ID);
        map2.put("type", OpenEnum.ZRX_QC_TYPE);
        map2.put("name", OpenEnum.ZRX_QC_NAME);
        list.add(map2);
        Map<String, Object> map3 = new HashMap<>();
        map3.put("app_id", OpenEnum.HSY_AD_APP_ID);
        map3.put("secret", OpenEnum.HSY_AD_SECRET);
        map3.put("access_token", OpenEnum.HSY_AD_ACCESS_TOKEN);
        map3.put("refreshToken", OpenEnum.HSY_AD_REFRESHTOKEN);
        map3.put("auth_code", "aa044529566fc45140a0a3f37b28a70135d05baa");
        map3.put("advertiser_id", OpenEnum.HSY_AD_ADVERTISER_ID);
        map3.put("type", OpenEnum.HSY_AD_TYPE);
        map3.put("name", OpenEnum.HSY_AD_NAME);
        list.add(map3);
        Map<String, Object> map4 = new HashMap<>();
        map4.put("app_id", OpenEnum.HSY_QC_APP_ID);
        map4.put("secret", OpenEnum.HSY_QC_SECRET);
        map4.put("access_token", OpenEnum.HSY_QC_ACCESS_TOKEN);
        map4.put("refreshToken", OpenEnum.HSY_QC_REFRESHTOKEN);
        map4.put("auth_code", "f20153c6efbf6ef2ff1f06cf8be6848b929f04fa");
        map4.put("advertiser_id", OpenEnum.HSY_QC_ADVERTISER_ID);
        map4.put("type", OpenEnum.HSY_QC_TYPE);
        map4.put("name", OpenEnum.HSY_QC_NAME);
        list.add(map4);

        return list;
    }

    public R refreshToken(Map<String, Object> map) throws ApiException {

        Oauth2RefreshTokenRequest oauth2RefreshTokenRequest = new Oauth2RefreshTokenRequest();
        oauth2RefreshTokenRequest.setAppId(Long.valueOf(map.get("app_id").toString()));
        oauth2RefreshTokenRequest.setRefreshToken(RedisUtils.getCacheObject(map.get("refreshToken").toString()));
        oauth2RefreshTokenRequest.setSecret(map.get("secret").toString());
        ApiClient apiClient = refreshTokenApi.getApiClient();
        String access_token = RedisUtils.getCacheObject(map.get("access_token").toString());
        apiClient.addDefaultHeader("Access-Token", access_token);
        apiClient.setDebugging(true);
        refreshTokenApi.setApiClient(apiClient);
        Oauth2RefreshTokenResponse response = refreshTokenApi.openApiOauth2RefreshTokenPost(oauth2RefreshTokenRequest);
        System.out.println(response);
        String accessToken = response.getData().getAccessToken();
        String refreshToken = response.getData().getRefreshToken();
        RedisUtils.setCacheObject(map.get("access_token").toString(),accessToken);
        RedisUtils.setCacheObject(map.get("refreshToken").toString(),refreshToken);
        return R.ok();
    }

    @Override
    public void getAccessToken(){
        List<Map<String, Object>> list = getParams();
        list.forEach(map ->{
            try {
                authCode(map);
            } catch (ApiException e) {
                throw new RuntimeException(e);
            }
        });
    }

    @Override
    public void oceanLog(){
        List<Long> ssss= new ArrayList<>();
        List<OceanAccountVo> oceanAccountVoList = iOceanAccountService.queryActiveList();
        oceanAccountVoList.forEach(oceanAccount->{
            Long page = 1L;
            Long totalNumber = 10L;
            Long cuont = 0L;
            while (cuont< totalNumber){
                String accessToken = "";
                if(oceanAccount.getAgentName().equals("众人行(西安)信息科技有限公司")){
                    if(oceanAccount.getAccountType().equals("AD")){
                        accessToken = RedisUtils.getCacheObject(OpenEnum.ZRX_AD_ACCESS_TOKEN);
                    }else{
                        accessToken = RedisUtils.getCacheObject(OpenEnum.ZRX_QC_ACCESS_TOKEN);
                    }
                }else{
                    if(oceanAccount.getAccountType().equals("AD")){
                        accessToken = RedisUtils.getCacheObject(OpenEnum.HSY_AD_ACCESS_TOKEN);
                    }else{
                        accessToken = RedisUtils.getCacheObject(OpenEnum.HSY_QC_ACCESS_TOKEN);
                    }
                }
                Date currentDate = new Date();
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(currentDate);
                calendar.add(Calendar.DAY_OF_MONTH, -1);
                Date previousDate = calendar.getTime();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String yesterdays = sdf.format(previousDate);
                String endTime = yesterdays + " 23:59:59";
                List<Long> objectId = null;

                Long pageSize = 100L;
                String startTime = yesterdays + " 00:00:00";
                ApiClient apiClient = searchV2Api.getApiClient();
                apiClient.addDefaultHeader("Access-Token", accessToken);
                apiClient.setDebugging(true);
                searchV2Api.setApiClient(apiClient);
                ToolsLogSearchV2Response response = null;
                try {
                    response = searchV2Api.openApi2ToolsLogSearchGet(oceanAccount.getAdvertiserId(), endTime, objectId, page, pageSize, startTime);


                } catch (ApiException e) {

                }
                if(!Objects.isNull(response) && response.getCode()==0){
                    System.out.println(response.getData().getPageInfo());
                    totalNumber = response.getData().getPageInfo().getTotalNumber();

                    List<ToolsLogSearchV2ResponseDataLogsInner> list = response.getData().getLogs();
                    list.forEach(item->{
                        OceanLogBo bo = new OceanLogBo();

                        //
                        bo.setAccountId(oceanAccount.getAdvertiserId().toString());
                        try {
                            String result = item.getContentLog().stream().collect(Collectors.joining(","));
                            bo.setContentTitle(item.getContentTitle());
                            bo.setContentLog(result);
                        }
                        catch (Exception e) {
                            bo.setContentTitle("信息携带非正常字符");
                            bo.setContentLog("信息携带非正常字符");
                        }

                        String op = item.getOperator();
                        bo.setObjectName(oceanAccount.getAgentName());
                        bo.setOperator(op);
                        bo.setObjectType(oceanAccount.getAccountType());
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                        try {
                            bo.setCreateTime(formatter.parse(item.getCreateTime()));
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }

                        //  bo.setObjectId(item.getObjectId().toString());
                        //    bo.setObjectType(item.getObjectType());
                        //    bo.setOptIp(item.getOptIp());
                        try {
                            iOceanLogService.insertByBo(bo);
                        }catch (Exception e) {

                        }

                    });
                    page = page +1;
                    cuont = cuont +100;

                }else{
                    cuont= cuont +99999;
                    ssss.add(oceanAccount.getAdvertiserId());

                }

            }
        });
    }

    public void authCode(Map<String, Object> map) throws ApiException {
        ApiClient apiClient = new ApiClient();
        apiClient.setBasePath("https://api.oceanengine.com");
        apiClient.addDefaultHeader("Access-Token", "test");
        apiClient.setDebugging(true);
        api.setApiClient(apiClient);
        List<Pair> query = new ArrayList<Pair>();
        Map<String, Object> queryParams = new HashMap<>();

        CommonResponse response = api.commonReq("POST", "/open_api/oauth2/access_token/", "application/json", null, null, map);
        System.out.println(response);

        String accessToken = response.getData().get("access_token").toString();
        String refresh_token = response.getData().get("refresh_token").toString();
        System.out.println(accessToken);

        RedisUtils.setCacheObject(map.get("access_token").toString(),accessToken);
        RedisUtils.setCacheObject(map.get("refreshToken").toString(),refresh_token);

    }


    public R addAccount(Map<String, Object> map) throws ApiException {

        boolean hasMore = true;
        Long page = null;
        String accessToken = RedisUtils.getCacheObject(map.get("access_token").toString());
        Long advertiserId = Long.valueOf(map.get("advertiser_id").toString());
        List<Long> companyIds = null;
        Long count = 2000L;
        Long cursor = null;
        AgentAdvertiserSelectV2Filtering filtering = null;
        Long pageSize = null;
        ApiClient apiClient = selectV2Api.getApiClient();
        apiClient.addDefaultHeader("Access-Token", accessToken);
        apiClient.setDebugging(true);
        selectV2Api.setApiClient(apiClient);
        while (hasMore){

            AgentAdvertiserSelectV2Response response = selectV2Api.openApi2AgentAdvertiserSelectGet(advertiserId, companyIds, count, cursor, filtering, page, pageSize);
            System.out.println(response);
            if(!Objects.isNull(response) && response.getCode()==0){

                hasMore = response.getData().getCursorPageInfo().getHasMore();
                cursor = response.getData().getCursorPageInfo().getCursor();
                List<Long> list = response.getData().getList();

                list.forEach(id ->{
                    int num = iOceanAccountService.queryByAdvertiserId(id);
                    if(num == 0){
                        OceanAccountBo oceanAccount = new OceanAccountBo();
                        oceanAccount.setAccountType(map.get("type").toString());
                        oceanAccount.setAgentName(map.get("name").toString());
                        oceanAccount.setAdvertiserId(id);
                        iOceanAccountService.insertByBo(oceanAccount);
                    }

                });
            }else{
                hasMore = false;
            }

        }


        return R.ok();
    }

    public void reportAgent() throws ApiException {
        List<Map<String, Object>> list =  getParams();
        for (Map<String, Object> stringObjectMap : list) {
            String type = stringObjectMap.get("type").toString();
            String name = stringObjectMap.get("name").toString();
            int num = iOceanAccountService.count(type,name);
            for (int i = 0; i < num; i=i+20) {
                List<OceanAccountVo> OceanAccountVos = iOceanAccountService.queryListByPage(i,20,type,name);
                busRun(OceanAccountVos);
            }

        }



    }
public void busRun(List<OceanAccountVo> oceanAccountVos) throws ApiException {
    Date today = new Date();   //当前时间
    Calendar calendar = Calendar.getInstance(); //得到日历
    calendar.setTime(today);//把当前时间赋给日历
    calendar.add(Calendar.DAY_OF_MONTH, -1);  //设置为前一天

    Date yesterday = calendar.getTime();   //得到前一天的时间
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); //设置时间格式
    String endDate = null;
    String startDate = null;
    List<Long> advertiserIds = new ArrayList<>();
    for (OceanAccountVo oceanAccountVo : oceanAccountVos) {
        advertiserIds.add(oceanAccountVo.getAdvertiserId());
    }
    Map<String, Object> params = getParamMap(oceanAccountVos.get(0).getAgentName(),oceanAccountVos.get(0).getAccountType());
    Long agentId = Long.valueOf(params.get("advertiser_id").toString());
    Long cursor = null;
    Long cursorSize = null;
    ReportAgentGetV2V2Filtering filtering = new ReportAgentGetV2V2Filtering();
    filtering.setAdvertiserIds(advertiserIds);
    Long page = null;
    Long pageSize = null;
    ApiClient apiClient = api.getApiClient();
    String access_token = RedisUtils.getCacheObject(params.get("access_token").toString());
    apiClient.addDefaultHeader("Access-Token", access_token);
    apiClient.setDebugging(true);
    api.setApiClient(apiClient);
    ReportAgentGetV2V2Response response = reportAgentGetV2V2Api.openApi2ReportAgentGetV2Get(agentId, cursor, cursorSize, endDate, filtering, page, pageSize, startDate);
    if(response.getCode() != null && response.getCode() == 0){
        List<ReportAgentGetV2V2ResponseDataListInner> res = response.getData().getList();
        for (ReportAgentGetV2V2ResponseDataListInner re : res) {
            if(re.getYesterdayCashCost()> 1){
                iOceanAccountService.updateYes(re.getAdvertiserId(),yesterday);
            }
        }
    }
}
// for (OceanAccountVo oceanAccountVo : list) {
//
//        Map<String, Object> params = getParamMap(oceanAccountVo.getAgentName(),oceanAccountVo.getAccountType());
//        Long agentId = Long.valueOf(params.get("advertiser_id").toString());
//        Long cursor = null;
//        Long cursorSize = null;
//        List<Long> advertiserIds = new ArrayList<>();
//        advertiserIds.add(oceanAccountVo.getAdvertiserId());
//        ReportAgentGetV2V2Filtering filtering = new ReportAgentGetV2V2Filtering();
//        filtering.setAdvertiserIds(advertiserIds);
//        Long page = null;
//        Long pageSize = null;
//        ApiClient apiClient = api.getApiClient();
//        String access_token = RedisUtils.getCacheObject(params.get("access_token").toString());
//        apiClient.addDefaultHeader("Access-Token", access_token);
//        apiClient.setDebugging(true);
//        api.setApiClient(apiClient);
//        ReportAgentGetV2V2Response response = reportAgentGetV2V2Api.openApi2ReportAgentGetV2Get(agentId, cursor, cursorSize, endDate, filtering, page, pageSize, startDate);
//        if(response.getCode() != null && response.getCode() == 0){
//            List<ReportAgentGetV2V2ResponseDataListInner> res = response.getData().getList();
//            if(res != null && !res.isEmpty()){
//                if(!Objects.isNull(res.get(0).getYesterdayCashCost()) && res.get(0).getYesterdayCashCost()> 1){
//                    //昨天有值
//                    oceanAccountVo.setActiveDate(yesterday);
//                    OceanAccountBo update = BeanUtil.toBean(oceanAccountVo, OceanAccountBo.class);
//                    iOceanAccountService.updateByBo(update);
//                }
//            }
//        }
//    }
   public Map<String, Object> getParamMap(String agentName,String accountType){

       List<Map<String, Object>> list = getParams();
       if("恒盛易（厦门）信息技术有限公司".equals(agentName)){
           //恒盛易（厦门）信息技术有限公司
           if("AD".equals(accountType)){
               return list.get(2);
           }else{
               return list.get(3);
           }
       }else{
           //众人行(西安)信息科技有限公司
           if("AD".equals(accountType)){
               return list.get(0);
           }else{
               return list.get(1);
           }
       }
    }
}
